var express = require('express');
var router = express.Router();
var Mongodb = require('../../database/mongodb');
const mongodb = require('mongodb');
var mongoose = require('mongoose');
const ObjectID = require('mongodb').ObjectID;
var conn = mongoose.connection;
const BizResult = require("../../service/BizResult");

const multer = require('multer');
var storage = multer.memoryStorage()
var upload = multer({ storage: storage, limits: { fields: 1, fileSize: 60000000000, files: 1, parts: 2 }});

/**
* NodeJS Module dependencies.
*/
const { Readable } = require('stream');

var iconv = require('iconv-lite');

function saveViewRecord (req, businessId) {
    let loginUser = req.cookies['user']
    if (loginUser) {
        let obj = {
            'businessId': businessId,
            'viewDate': new Date(),
            'viewUser': loginUser.email
        }
        Mongodb.save('viewRecord', obj);
    }
    
}

/**
 * GET photo by ID Route
 */
 router.get('/:id/:filename', (req, res) => {
    try {
        var fileId = new ObjectID(req.params.id);
    } catch(err) {
        return res.status(400).json({ message: "Invalid fileId in URL parameter. Must be a single String of 12 bytes or a string of 24 hex characters" });
    }
    
    let bucket = new mongodb.GridFSBucket(conn.db, {
        bucketName: 'files'
    });
    
    var cursor = bucket.find({ _id: fileId })
    cursor.on('data', (file) => {
        // 图片和PDF浏览器直接打开，其他文件下载
        if ((file.contentType.indexOf('image') < 0) && (file.contentType.indexOf('pdf') < 0)) {
            console.log("下载");
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(file.filename));
        } else {
            console.log('图片，pdf')
            res.setHeader('Content-Type', file.contentType);
            res.setHeader('Content-Disposition', 'inline');
        }
        let downloadStream = bucket.openDownloadStream(fileId);
        downloadStream.on('data', (chunk) => {
            res.write(chunk);
        });
        
        downloadStream.on('error', () => {
            res.sendStatus(404);
        });
        
        downloadStream.on('end', () => {
            saveViewRecord(req, fileId)
            res.end();
        });
    })
});

/**
 * GET photo by ID Route
 */
router.get('/:id', (req, res) => {
    try {
        var fileId = new ObjectID(req.params.id);
    } catch(err) {
        return res.status(400).json({ message: "Invalid fileId in URL parameter. Must be a single String of 12 bytes or a string of 24 hex characters" });
    }
    
    let bucket = new mongodb.GridFSBucket(conn.db, {
        bucketName: 'files'
    });
    
    console.log("文件ID：" + fileId)
    var cursor = bucket.find({ _id: fileId })
    cursor.on('data', (file) => {
        // 图片和PDF浏览器直接打开，其他文件下载
        if (!isWordFile(file.filename) && (file.contentType.indexOf('image') < 0) && (file.contentType.indexOf('pdf') < 0) && (file.contentType.indexOf('video') < 0)) {
            console.log("下载");
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(file.filename));
        } else {
            res.setHeader('Content-Type', file.contentType);
            res.setHeader('Content-Disposition', 'inline');
        }
        let downloadStream = bucket.openDownloadStream(fileId);
        downloadStream.on('data', (chunk) => {
            res.write(chunk);
        });
        
        downloadStream.on('error', () => {
            res.sendStatus(404);
        });
        
        downloadStream.on('end', () => {
            saveViewRecord(req, fileId)
            res.end();
        });
    })
});


function isWordFile(filename) {
    const extension = filename.split('.').pop().toLowerCase();
    return extension === 'docx' || extension === 'doc';
}

/**
 * DELETE file by ID
 */
router.get('/delete/:id', (req, res) => {
    try {
        var fileId = new ObjectID(req.params.id);
    } catch(err) {
        return res.status(400).json({ message: "Invalid fileId in URL parameter. Must be a single String of 12 bytes or a string of 24 hex characters" });
    }
    
    let bucket = new mongodb.GridFSBucket(conn.db, {
        bucketName: 'files'
    });
    
    bucket.delete(fileId, (err) => {
        if (err) {
            res.status(500).json({ message: "Error delete file" });
        } else {
            res.status(200).json({ message: "delete success" });
        }
    })
});

/**
 * POST photo Route
 */
router.post('/upload', (req, res) => {
    upload.single('file')(req, res, (err) => {
        console.log(req.file);
        var fileName = req.file.originalname
        
        if (err) {
            return res.status(400).json({ message: "Upload Request Validation Failed" });
        } else if(!req.file.originalname) {
            return res.status(400).json({ message: "No photo name in request body" });
        }
        
        // Covert buffer to Readable Stream
        const readablePhotoStream = new Readable();
        readablePhotoStream.push(req.file.buffer);
        readablePhotoStream.push(null);
        
        let bucket = new mongodb.GridFSBucket(conn.db, {
            bucketName: 'files'
        });
        
        let uploadStream = bucket.openUploadStream(fileName, {
            contentType: req.file.mimetype,
            aliases: [
                { fileName: fileName }
            ]
        });
        let id = uploadStream.id;
        readablePhotoStream.pipe(uploadStream);
        
        uploadStream.on('error', () => {
            return res.status(500).json({ message: "Error uploading file" });
        });
        
        uploadStream.on('finish', () => {
            return res.json(BizResult.success({ 
                id: id
                // fileUrl: "http://localhost:5000/works/file/" + id
             }));
        });
    });
});

module.exports = router;